import pymysql
from pymysql import Error
from db.conn_mysql import create_connection
from utils.config import load_config


def create_database(connection, db_name):
    """创建数据库"""
    config = load_config()
    db_name = config['mysql']['database']
    cursor = connection.cursor()
    try:
        cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name}")
        print(f"数据库 '{db_name}' 创建成功")
    except Error as e:
        print(f"创建数据库时发生错误: {e}")


def execute_query(connection, query):
    """执行 SQL 查询"""
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        connection.commit()
        print("查询执行成功")
    except Error as e:
        print(f"执行查询时发生错误: {e}")


def initialize_database():
    connection = create_connection()
    """初始化数据库表"""
    create_table_query = """
    CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(100) NOT NULL,
        email VARCHAR(100) NOT NULL UNIQUE,
        phone VARCHAR(100),
        password VARCHAR(512) NOT NULL
    )
    """
    execute_query(connection, create_table_query)
